<?php

use yii\helpers\Html;

use backend\assets\WechatAppset;

WechatAppset::register($this);
/* @var $this yii\web\View */
/* @var $model common\models\wechat\WechatMenus */

$this->title = '更新微信菜单: ' . $model->title;
$this->params['breadcrumbs'][] = ['label' => 'Wechat Menuses', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->title, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = 'Update';
//var_dump($menu);exit;
?>



<?= $this->render('_menu', [
    'type' => $type,
    'id' => $id,
    'params' => $params,
    'menu' => $menu,
    'groups' => $groups,
    'model' => $model,
]) ?>


<script type="text/javascript">
    <?php $this->beginBlock('jsend'); ?>


    require(["angular", "underscore", "jquery.ui", "jquery.caret", 'district'], function (angular, _, $, $, dis) {
        $(".tpl-district-container").each(function () {
            var elms = {};
            elms.province = $(this).find(".tpl-province")[0];
            elms.city = $(this).find(".tpl-city")[0];
            var vals = {};
            vals.province = $(elms.province).attr("data-value");
            vals.city = $(elms.city).attr("data-value");
            dis.render(elms, vals, {withTitle: true});
        });
        angular.module('app', []).controller('conditionMenuDesigner', function ($scope, $http) {
            $scope.context = {};
            $scope.context.group = <?= !empty($params) ? json_encode($params) : "null" ?>;
            console.log($scope.context.group);
            console.log($scope.context.group);
            <?php if($id > 0 && $type != 1) { ?>
                $scope.context.group.disabled = 1;
                $scope.context.group.isgexing = 1;
            <?php } ?>
            if (!$scope.context.group) {
                $scope.context.group = {
                    title: '标题',
                    type: "{$type}",
                    button: [{
                        name: '菜单名称',
                        type: 'url',
                        url: '',
                        key: '',
                        media_id: '',
                        sub_button: []
                    }],
                    matchrule: {
                        sex: 0,
                        client_platform_type: 0,
                        group_id: -1,
                        country: '',
                        province: '',
                        city: ''
                    }
                };
                if ($scope.context.group.type == 1) {
                    $scope.context.group.title = '系统默认菜单';
                } else if ($scope.context.group.type == 2) {
                    $scope.context.group.title = '个性化菜单';
                }
            }
            $scope.context.activeIndex = 0;
            $scope.context.activeBut = $scope.context.group['button'][$scope.context.activeIndex];
            $scope.context.activeItem = $scope.context.activeBut;
            $scope.context.activeType = 1; //标识一级菜单
            //删除默认菜单
            $scope.context.remove = function () {
                if (!confirm('删除默认菜单会清空所有菜单记录，确定吗？')) {
                    return false;
                }
                location.href = "{php echo url('platform/menu/remove', array('id' => $id));}";
                return false;
            };

            $scope.context.submit = function () {
                var group = $scope.context.group;
                group.button = _.sortBy(group.button, function (h) {
                    var elm = $(':hidden[data-role="parent"][data-hash="' + h.$$hashKey + '"]');
                    return elm.parent().index();
                });
                angular.forEach(group.button, function (j) {
                    j.sub_button = _.sortBy(j.sub_button, function (h) {
                        var e = $(':hidden[data-role="sub"][data-hash="' + h.$$hashKey + '"]');
                        return e.parent().index();
                    });
                });

                if (!$.trim(group.title)) {
                    console.log('没有设置标题');

                    util.message('没有设置标题', '', 'error');
                    return false;
                }
                <?php if($type == 2) { ?>
                if (!group.matchrule.sex && !group.matchrule.client_platform_type && group.matchrule.group_id == -1 && !group.matchrule.province && !group.matchrule.city) {
                    util.message('没有设置个性化菜单的匹配规则', '', 'error');
                    console.log('没有设置个性化菜单的匹配规则');
                    return false;
                }
                <?php } ?>
                if (group.button.length < 1) {
                    util.message('没有设置菜单', '', 'error');
                    console.log('没有设置菜单');
                    return false;
                }
                var error = {name: '', action: ''};
                angular.forEach(group.button, function (val, index) {
                    if ($.trim(val.name) == '') {
                        this.name += '第' + (index + 1) + '个一级菜单未设置菜单名称<br>';
                    }
                    if (val.sub_button.length > 0) {
                        angular.forEach(val.sub_button, function (v, index1) {
                            if ($.trim(v.name) == '') {
                                this.name += '第' + (index + 1) + '个一级菜单中的第' + (index1 + 1) + '个二级菜单未设置菜单名称<br>';
                            }
                            if ((v.type == 'view' && $.trim(v.url) == '') || ((v.type != 'view' && v.type != 'media_id' && v.type != 'view_limited') && $.trim(v.key) == '') || ((v.type == 'media_id' || v.type == 'view_limited') && !$.trim(v.media_id))) {
                                this.action += '菜单【' + val.name + '】的子菜单【' + v.name + '】未设置操作选项. <br />';
                            }
                        }, error);
                    } else {
                        console.dir(val);
                        if ((val.type == 'view' && $.trim(val.url) == '') || ((val.type != 'view' && val.type != 'media_id' && val.type != 'view_limited') && $.trim(val.key) == '') || ((val.type == 'media_id' || val.type == 'view_limited') && !$.trim(val.media_id))) {
                            this.action += '菜单【' + val.name + '】不存在子菜单并且未设置操作选项. <br />';
                        }
                    }
                }, error);

                if (error.name) {
                    console.log(error.title);
                    util.message(error.title, '', 'error');
                    return;
                }
                if (error.action) {
                    console.log(error.action);
                    util.message(error.action, '', 'error');
                    return;
                }
                $('#btn-submit').attr('disabled', true);
                $http.post("<?= \yii\helpers\Url::to(['/wechat/menus/save']) ?>", {
                    group: group,
                    method: 'save',
                }).success(function (dat) {
                    if (dat.errno != 0) {
                        $('#btn-submit').attr('disabled', false);
                        console.log(dat.message);
                        util.message(dat.message.message, '', 'error');
                    } else {
                        console.log('创建菜单成功');
                        util.message('创建菜单成功. ', "index", 'success');
                    }
                });
            }

            $scope.context.triggerActiveBut = function (but) {
                var index = $.inArray(but, $scope.context.group.button);
                if (index == -1) return false;
                $scope.context.activeIndex = index;
                $scope.context.activeBut = $scope.context.group['button'][$scope.context.activeIndex];
                $scope.context.activeItem = $scope.context.activeBut;
                $scope.context.activeType = 1;
            };

            $scope.context.editBut = function (subbut, but) {
                console.log(but);
                $scope.context.triggerActiveBut(but);
                if (!subbut) {
                    $scope.context.activeItem = but;
                    $scope.context.activeType = 1;
                } else {
                    $scope.context.activeItem = subbut;
                    $scope.context.activeType = 2;
                }
            };

            $scope.context.addBut = function () {
                if ($scope.context.group['button'].length >= 3) {
                    return;
                }
                $scope.context.group['button'].push({
                    name: '菜单名称',
                    type: 'view',
                    url: '',
                    key: '',
                    media_id: '',
                    sub_button: []
                });
                var but = $scope.context.group['button'][$scope.context.group.button.length - 1];
                $scope.context.triggerActiveBut(but);
                $('.designer-x').sortable({
                    items: '.js-sortable',
                    axis: 'x'
                });
            }

            $scope.context.removeBut = function (but, type) {
                if (type == 1) {
                    if (!confirm('将同时删除所有子菜单,是否继续')) {
                        return false;
                    }
                    $scope.context.group.button = _.without($scope.context.group.button, but);
                    $scope.context.triggerActiveBut($scope.context.group['button'][0]);
                } else {
                    $scope.context.activeBut.sub_button = _.without($scope.context.activeBut.sub_button, but);
                    $scope.context.triggerActiveBut($scope.context.activeBut);
                }
            };

            $scope.context.addSubBut = function (but) {
                $scope.context.triggerActiveBut(but);
                if ($scope.context.activeBut.sub_button.length >= 5) {
                    return;
                }
                $scope.context.activeBut.sub_button.push({
                    name: '子菜单名称',
                    type: 'url',
                    url: '',
                    key: '',
                    media_id: ''
                });
                $('.designer-y').sortable({
                    items: 'dd',
                    axis: 'y',
                    cancel: '.js-not-sortable'
                });
                $scope.context.activeItem = $scope.context.activeBut.sub_button[$scope.context.activeBut.sub_button.length - 1];
                $scope.context.activeType = 2;
            }

            /*选择Emoji表情*/
            $scope.context.selectEmoji = function () {
                util.emojiBrowser(function (emoji) {
                    var text = '::' + emoji.find("span").text() + '::';
                    $('#title').setCaret();
                    $('#title').insertAtCaret(text);
                    $scope.context.activeItem.name = $('#title').val();
                    $scope.$digest();
                });
            };

            //点击选择【系统连接】事件
            $scope.context.select_link = function () {
                var ipt = $(this).parent().prev();
                util.linkBrowser(function (href) {
                    var site_url = "{$_W['siteroot']}";
                    if (href.substring(0, 4) == 'tel:') {
                        util.message('自定义菜单不能设置为一键拨号');
                        return;
                    } else if (href.indexOf("http://") == -1 && href.indexOf("https://") == -1) {
                        href = href.replace('./index.php?', '/index.php?');
                        href = site_url + 'app' + href;
                    }
                    $scope.context.activeItem.url = href;
                    $scope.$digest();
                });
            };

            $scope.context.search = function () {
                var search_value = $('#ipt-forward').val();
                $.post("search-kwd", {'key_word': search_value}, function (data) {
                    var data = $.parseJSON(data);
                    var total = data.length;
                    var html = '';
                    if (total > 0) {
                        for (var i = 0; i < total; i++) {
                            html += '<li><a href="javascript:;">' + data[i] + '</a></li>';
                        }
                    } else {
                        html += '<li><a href="javascript:;" id="no-result">没有找到您输入的关键字</a></li>';
                    }
                    $('#key-result ul').html(html);
                    $('#key-result ul li a[id!="no-result"]').click(function () {
                        $('#ipt-forward').val($(this).html());
                        $scope.context.activeItem.key = $(this).html();
                        $('#key-result').hide();
                    });
                    $('#key-result').show();
                });
            };

            $scope.context.select_mediaid = function () {
                var option = {
                    'ignore': {
                        'wxcard': true
                    }
                };
                if ($scope.context.activeItem.type == 'view_limited') {
                    option.ignore = {
                        'image': true,
                        'voice': true,
                        'video': true,
                        'wxcard': true
                    };
                }
                util.material(function (material) {
                    $scope.context.activeItem.media_id = material.media_id;
                    $scope.$digest();
                }, option);
            };
        });
        angular.bootstrap($('#conditionMenuDesigner')[0], ['app']);
        $(function () {
            $('.designer-y').sortable({
                items: 'dd',
                axis: 'y',
                cancel: '.js-not-sortable'
            });
            $('.designer-x').sortable({
                items: '.js-sortable',
                axis: 'x'
            });
        });
    });
    <?php $this->endBlock('jsend') ?>
    <?php $this->registerJs($this->blocks['jsend'], \yii\web\View::POS_END) ?>
</script>